import {_filename,byFile} from '../utils/tool.js';

let filname=_filename(import.meta.url);

let shortname=byFile(filname);

let goods=[
    {
        id:1,
        filename:"乐事薯片",
        year:"2"
    },
    {
        id:2,
        filename:"八宝粥",
        year:"10"
    },
    {
        id:3,
        filename:"干货",
        year:"18"
    },
    {
        id:4,
        filename:"文具",
        year:"8"
    },
    {
        id:5,
        filename:"水果",
        year:"0.2"
    },
]

//http://localhost:8080/goods

async function fn_getAll(ctx){
    let keyword =ctx.request.query.keyword|| "";
    keyword=keyword.trim();//删除空格
    if(keyword){
        let list =goods.filter(item=>{
            return item.filename.includes(keyword)|| item.year.includes(keyword)
        })
    
    ctx.body={
        code:1000,
        data:list,
        msg:'查找数据成功'
    }
    }else{
        ctx.body={
            code:1000,
            data:goods,
            msg:'获取所有商品成功'
        }
    }
}

async function fn_getById(ctx){
    let id=ctx.params.id*1 || 0;
    let arr=goods.filter(item=>{
        return item.id===id;
    });
    let res={
        code:1000,
        data:arr[0],
        msg:`获取指定${id}的商品名称成功`
    }
    ctx.body=res;
}

async function fn_post(ctx){
    let obj=ctx.request.body;
    let lastid=goods[goods.length];
    obj['id']=lastid;
    goods.push(obj);
    ctx.body=obj;
};

async function fn_put(ctx){
    let id=ctx.params.id *1 || 0;
    let reqparm=ctx.request.body;
    let arr=goods.filter(item=>{
        return item.id===id;
    });
    if(arr.length>0){
        let obj=arr[0];
        obj.filename=reqparm.filename;
        obj.year=reqparm.year;
        ctx.body={
            code:1000,
            msg:'修改成功'
        }
    }else{
        ctx.body={
            code:4000,
            msg:`没有找到ID为${id}的商品，请重试`
        }
    }
}

async function fn_del(ctx){
    let id=ctx.params.id *1 || 0;
    let arr=goods.filter(item=>{
        return item.id===id;
    });
    let idx=arr.findIndex(item=>{
        return item.id===id;
    })
    if(arr.length>0){
        goods.splice(idx,1);
        ctx.body={
            code:1000,
            msg:`删除id为${id}的商品成功`
        }
    }else{
        ctx.body={
            code:3000,
            msg:'未找到'
        }
    }
}

let obj=[];

obj[`get /${shortname}`]=fn_getAll;
obj[`get /${shortname}/:id?`]=fn_getById;
obj[`post /${shortname}`]=fn_post;
obj[`put /${shortname}/:id?`]=fn_put;
obj[`del /${shortname}/:id?`]=fn_del;

export default obj;